package com.yswy.common.utils;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.UUID;

/**
 * 文件下载
 **/
public class DownloadURLFile {



//    /**
//     * @param args
//     */
//    public static void main(String[] args) throws IOException {
//        String res = downloadFromUrl("https://zhijian-platform.obs.cn-south-1.myhuaweicloud.com:443/pcm%2F5e469f4e-4c4e-43ef-aebd-6d042caacae5_4d4b59fe-3121-4448-a5ed-295273c8b568%25E9%25B1%25BC.m4a.pcm","e:/upload/");
//        System.out.println(res);
//    }


    /**
     * 指定目录,通过url下载文件,并返回文件地址
     * @Author baoruizhe
     * @Date 15:35 2020/9/7
     * @Param [url, dir]
     * @return java.lang.String
     **/
    public static String downloadFromUrl(String url, String dir) throws IOException {
        URL httpurl = new URL(url);
        String fileName = getFileNameFromUrl(url);

        //System.out.println(fileName);
        File f = new File(dir + fileName);
        FileUtils.copyURLToFile(httpurl, f);
        return dir + fileName;
    }


//    public static void main(String[] args) throws IOException {
//        String res = DownloadURLFile.downloadFromUrl("https://zhijian-platform.obs.cn-south-1.myhuaweicloud.com:443/file%2Finrt.apk", "e:/upload/");
//    }

    /**
     * 指定目录,通过url下载文件,并返回文件地址
     * @Author baoruizhe
     * @Date 15:35 2020/9/7
     * @Param [url, dir]
     * @return java.lang.String
     **/
    public static String downloadFromUrlromName(String url, String dir) throws IOException {
        URL httpurl = new URL(url);
        String fileName = getFileNameFromUrl(url);
        String[] filenames = fileName.split("\\.");
        fileName = UUID.randomUUID().toString().replace("-","")+"."+filenames[1];
        //System.out.println(fileName);
        File f = new File(dir + fileName);
        FileUtils.copyURLToFile(httpurl, f);
        return dir + fileName;
    }



    public static String getFileNameFromUrl(String url) {
        String name = new Long(System.currentTimeMillis()).toString() + ".X";
        String theUrl = url.split("\\?")[0];
        int index = theUrl.lastIndexOf("/");
        if (index > 0) {
            name = theUrl.substring(index + 1);
            if (name.trim().length() > 0) {
                return name;
            }
        }
        return name;
    }


}
